package com.losdun.product.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.losdun.common.utils.DateUtils;
import com.losdun.product.domain.Category;
import com.losdun.product.domain.Product;
import com.losdun.product.domain.vo.ProductAttributeVo;
import com.losdun.product.domain.vo.SkuVo;
import com.losdun.product.domain.vo.TreeSelectVo;
import com.losdun.product.enums.ProductTypeEnum;
import com.losdun.product.mapper.ProductMapper;
import com.losdun.product.service.ICategoryService;
import com.losdun.product.service.IProductService;
import com.losdun.product.service.ProductAttributeService;
import com.losdun.product.service.ProductSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 产品Service业务层处理
 * 
 * @author sword.ye
 * @date 2025-02-27
 */
@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductMapper,Product> implements IProductService
{
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuService productSkuService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private ProductAttributeService productAttributeService;

    /**
     * 查询产品
     * 
     * @param id 产品主键
     * @return 产品
     */
    @Override
    public Product selectProductById(Long id)
    {
        Product product = productMapper.selectProductById(id);
        if(ProductTypeEnum.MULTI_SKU.getValue().equals(product.getType())){
            product.setAttributes(JSON.parseArray(product.getAttributesJson(), TreeSelectVo.class));
            List<SkuVo> skus=productSkuService.querySkusVoByProductId(product.getId());
            product.setSkus(skus);
            List<ProductAttributeVo> prodAttrList = productAttributeService.queryAttributesByProductId(product.getId());
            product.setProdAttrList(prodAttrList);
        }
        Category cate = categoryService.selectCategoryById(product.getCategoryId());
        product.setCategoryName(cate!=null?cate.getName():null);
        product.setCategoryRemark(cate!=null?cate.getRemark():null);
        product.setCategory(cate);
        return product;
    }

    /**
     * 查询产品列表
     * 
     * @param product 产品
     * @return 产品
     */
    @Override
    public List<Product> selectProductList(Product product)
    {
        List<Product> prodcutList = productMapper.selectProductList(product);
        prodcutList.forEach(item->{
            item.setMinPrice(item.getPrice());
            Category cate = categoryService.selectCategoryById(item.getCategoryId());
            item.setCategoryName(cate!=null?cate.getName():null);
            if(cate!=null){
                Category parent = categoryService.selectCategoryById(cate.getParentId());
                cate.setParentName(parent!=null?parent.getName():null);
            }
            item.setCategory(cate);
            /*if(ProductTypeEnum.MULTI_SKU.getValue().equals(product.getType())){
                BigDecimal minPrice = productSkuService.queryMinPrice(Collections.singletonList(item.getId()));
                item.setMinPrice(minPrice);
            }else{
                item.setMinPrice(item.getPrice());
            }*/
        });
        return prodcutList;
    }

    /**
     * 新增产品
     * 
     * @param product 产品
     * @return 结果
     */
    @Override
    public int insertProduct(Product product)
    {
        product.setAttributesJson(JSON.toJSONString(product.getAttributes()));
        product.setCreateTime(DateUtils.getNowDate());
        int ret=productMapper.insertProduct(product);
        //多属性产品
        if(ProductTypeEnum.MULTI_SKU.getValue().equals(product.getType()) && ret>0){
            //保存属性
            productAttributeService.batchInsert(product.getId(), product.getAttributes());
            //保存SKU
           boolean result= productSkuService.batchInsert(product.getId(),product.getSkus());
            if (result) {
                log.info("sku保存成功");
            } else {
                log.info("sku保存失败");
            }

            Optional<SkuVo> min = product.getSkus().stream().min(Comparator.comparing(p ->
                    p.getPrice() != null ? p.getPrice() : BigDecimal.ZERO
            ));
            min.ifPresent(skuVo -> this.updateProductPrice(product.getId(), skuVo.getPrice()));
        }
        return ret;
    }

    /**
     * 修改产品
     * 
     * @param product 产品
     * @return 结果
     */
    @Override
    public int updateProduct(Product product)
    {
        product.setAttributesJson(JSON.toJSONString(product.getAttributes()));
        product.setUpdateTime(DateUtils.getNowDate());
        int ret=productMapper.updateProduct(product);
        //多属性产品
        if(ProductTypeEnum.MULTI_SKU.getValue().equals(product.getType()) && ret>0){
            productAttributeService.batchUpdate(product.getId(), product.getAttributes());
            productSkuService.batchUpdate(product.getId(),product.getSkus());
            Optional<SkuVo> min = product.getSkus().stream().min(
                    Comparator.comparing(p ->p.getPrice() != null ? p.getPrice() : BigDecimal.ZERO
            ));
            min.ifPresent(skuVo -> this.updateProductPrice(product.getId(), skuVo.getPrice()));

        }
        return ret;
    }

    /**
     * 批量删除产品
     * 
     * @param ids 需要删除的产品主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProductByIds(Long[] ids)
    {
        productMapper.deleteProductByIds(ids);
        for(Long id:ids){
            productSkuService.removeByProductId(id);
            productAttributeService.removeByProductId(id);
        }
        return ids.length;
    }

    /**
     * 删除产品信息
     * 
     * @param id 产品主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProductById(Long id)
    {
        productMapper.deleteProductById(id);
        productSkuService.removeByProductId(id);
        productAttributeService.removeByProductId(id);
        return 1;
    }

    @Override
    public List<Long> getProductIdByCategoryId(Long categoryId) {
        Product product=new Product();
        product.setCategoryId(categoryId);
        List<Product> prodcutList = productMapper.selectProductList(product);
        if (prodcutList != null && !prodcutList.isEmpty()) {
            return prodcutList.stream().map(Product::getId).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }


    @Override
    public BigDecimal getProductMinPrice(Long categoryId) {
        return productMapper.queryProductMinPrice(categoryId);
    }

    /**
     * 更新价格
     * @param prodId
     * @param price
     */
    private void updateProductPrice(Long prodId,BigDecimal price){
        Product product = new Product();
        product.setId(prodId);
        product.setPrice(price);
        productMapper.updateProduct(product);
    }

}
